﻿using iText.Forms;
using iText.IO.Font;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.XMP;
using iText.Layout.Element;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SZHelperCore
{
    public class PdfFonts
    {
        private static PdfFont GetFont(string name)
        {
            var fontPath= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fonts\\", name);
            // 加载字体
            var fontProgram = FontProgramFactory.CreateFont(fontPath);
            return PdfFontFactory.CreateFont(fontProgram, PdfEncodings.IDENTITY_H);
        }
        public static PdfFont FangSong
        {
            get
            {
                return GetFont("fangsong.ttf");
            }
        }
        public static PdfFont KaiTi
        {
            get
            {
                return GetFont("kaiti.ttf");
            }
        }
        public static PdfFont SongTi
        {
            get
            {
                return GetFont("songti.ttf");
            }
        }
        public static PdfFont YaHei
        {
            get
            {
                return GetFont("yahei.ttf");
            }
        }
    }
    public class PdfHelper:IDisposable
    {
        //读取文件相关的表单
        PdfDocument pdf;
        PdfReader pdfReader;
        PdfWriter pdfWriter;
        MemoryStream ms;
        PdfFont systemfont;

        public PdfHelper(string pdfPath, string password = null)
        {
            if(!string.IsNullOrEmpty(password))
            {
                ReaderProperties props = new ReaderProperties();
                props.SetPassword(Encoding.UTF8.GetBytes(password));
                pdfReader = new PdfReader(pdfPath, props);
            }
            else
            {
                pdfReader = new PdfReader(pdfPath);
            }
            ms = new MemoryStream();
            pdfWriter = new PdfWriter(ms);
            pdf =new PdfDocument(pdfReader, pdfWriter);
            systemfont = PdfFonts.SongTi;
        }
        public void SetFont(PdfFont pdfFont)
        {
            systemfont=pdfFont;
        }
        public void SetValues<T>(T obj)
        {
            var properties = obj.GetType().GetProperties();
            Dictionary<string, string> forms = new Dictionary<string, string>();
            foreach (var prop in properties)
            {
                var value = prop.GetValue(obj);
                if(value != null)
                forms.Add(prop.Name,value.ToString());
            }
            SetValues(forms);
        }
        public void SetValues(Dictionary<string,string>  keyValuePairs)
        {
            var forms = PdfAcroForm.GetAcroForm(pdf, true);
            var fields = forms.GetAllFormFields();
            //遍历表单域进行填充
            foreach (var field in fields)
            {
                //在Dictionary中查找有无对应域的数据
                if (keyValuePairs.TryGetValue(field.Key, out string value))
                {
                    //填充表单、设置字体、设置只读
                    field.Value
                        .SetValue(value)
                         .SetFont(systemfont);
                    field.Value.SetReadOnly(true);
                }

            }
        }
        public byte[] SaveAsByte()
        {
            if (pdf != null)
            {
                pdf.Close();
                pdf = null;
            }
           
            return ms.ToArray();
        }
        public string SaveAsFile(string savePath, string fileName = "")
        {
            if (pdf != null)
            {
                pdf.Close();
                pdf = null;
            }
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = Guid.NewGuid() + ".pdf";
            }
            string savedFileName = SaveStreamToFile(savePath, fileName);
            return savedFileName;
        }

        public string SaveStreamToFile(string savePath, string fileName)
        {
            // 确保目录存在
            DirectoryInfo di = new DirectoryInfo(savePath);
            if (!di.Exists)
            {
                di.Create();
            }

            // 将 MemoryStream 转换为字节数组
            byte[] buffer = ms.ToArray();

            // 使用 Path.Combine 更安全
            string filePath = Path.Combine(savePath, fileName);

            // 写入文件
            File.WriteAllBytes(filePath, buffer);

            return fileName;
        }

        public void Dispose()
        {
            if(pdf!=null)
            {
                pdf.Close();
                pdf = null;
                pdfReader.Close();
                pdfWriter.Close();

                pdfReader = null;
                pdfWriter = null;
            }
            
            
        }
    }
}
   